from flask.wrappers import Response
import sqliteTools
import baseTools
import gitPython
import copyFile

from flask import Flask, request, jsonify
import json
import os
from git import Repo
import git
import shutil
from flask_cors import CORS
from git import Git
import re


import sqlite3
import os
import os.path as osp

app = Flask(__name__)
CORS(app, resources=r'/*')   


def isNullString(value,default):
    if value is None:
         return default
    else:
         return value

regex = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
        r'localhost|' #localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
        r'(?::\d+)?' # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)        

# values = sqliteTools.queryKeyvalues(database='poddata.db',table='pod_trace_log')

# arr=[]
# for i in values:
#          arr.append({'id':i[0],'podName':i[2],'podSource':i[3],'auth':i[5],'podEmail':i[6]})
# print(arr)

# 制作接口
@app.route('/create/binary',methods=['post'])
def create_binary(): 
    Response
    main_id = isNullString(value=request.form.get('id'),default="")
    binary = isNullString(value=request.form.get('binary'),default="")

    if main_id.isalnum() is False:
          return json.dumps({'status':400,'message':'主键id不为空'},ensure_ascii=False)
    database_connect, database_cur = sqliteTools.connectDB(database='poddata.db')
    results = database_cur.execute("select * from %s where id=(%s)" %('pod_trace_log',main_id))
    
    for i in results:
        print(i)
        source_url = i[4]
        # repo_path1 = os.path.join('./gitBinary', i[2])
        # sqliteTools.mkdir(repo_path1)
        remoteTags = []
        repo_path = os.path.join('./git', i[2])
        if os.path.exists(repo_path):
            # 移除文件，防止无权限访问
            shutil.rmtree(repo_path)
            # new_repo = git.Repo.clone_from(source_url, repo_path)
            remoteTags = gitPython.gitClone(source_url,repo_path)
            
        else:
            remoteTags = gitPython.gitClone(source_url,repo_path)    

        # 判断podsepc 版本是否含有Binary    
        # podFile = "%s.podspec"%(i[2])
        podspec_path = './git/%s/%s.podspec'%(i[2],i[9]) #'./git/moduleManager/ModuleManager.podspec'
        build_pod = './git/%s/build_pod.sh'%(i[2]) #'./git/moduleManager/build_pod.sh'

        # 版本号是否存在Binary,版本号是否存在,版本号,真实版本号(True, True, '0.1.27','0.1.27Binary')
        result = copyFile.contain_binary(podspec_path,'Binary')

        for tag in remoteTags:
            if binary == 'Binary':
                if result[3] in '%s'%(tag) and 'Binary' in result[3]:
                    print(tag )
                    print('=======555' )
                    print(result[2] )
                    return json.dumps({'status':400,'message':'分支已存在'},ensure_ascii=False)
            else:
                if result[2] in '%s'%(tag):
                    print(tag )
                    print('=======' )
                    print(result[2] )
                    return json.dumps({'status':400,'message':'tag标签已存在，请更新标签'},ensure_ascii=False)
        # copyFile.replace_version
        version = '%sBinary'%(result[2])
        
        #判断是否是源码或二进制
        if binary == 'Binary':
            if result[0] is False and result[1] is True :
                print('55555')
                copyFile.replace_version(podspec_path,result[2],version)
                copyFile.replace_version(build_pod,result[2],version)
            if result[1] is False :
                return json.dumps({'status':400,'message':'podSpec文件格式有误'},ensure_ascii=False)
        else: 
            if result[0] == True:
               print('4444444')
               copyFile.replace_version(podspec_path,version,result[2])
               copyFile.replace_version(build_pod,version,result[2])

        os.chdir(repo_path) 
        if binary == 'Binary':
           os.system('./build_lib.sh')
        os.system('./build_pod.sh')
           

        #     # new_repo = git.Repo.clone_from(source_url, repo_path)
        # # 判断git仓库是否存在
        # if os.path.exists(repo_path):
        #     # 防止文件拒绝访问
        #     shutil.rmtree(path)
        #     print('pppppppp移除')
        #     # os.remove('git')
        #     gitPython.gitClone(source_url,repo_path)
        #     # new_repo = git.Repo.clone_from(source_url, repo_path)
        # else:
        #     print('pppppppp不溢出')
           
       

        # os.system('build_lib.sh')

        print('结束')

        return json.dumps({'status':200,'message':'成功'},ensure_ascii=False)

        # copy file
        result = baseTools.list_file_name(repo_path) 
        for item in result:
            if item.startswith('.git'):
             continue
            filePath = './git/' + i[2] + '/' + item
            newPath = './gitBinary/' + i[2] + '/' 
            newPathFile = './gitBinary/' + i[2] + '/'  + item
            baseTools.copyAllFiletoPath(filePath,newPath,newPathFile)
        
        # os.makedirs("./git/%s"%(i[2]))
        # new_repo = git.Repo.clone_from(url=source_url, to_path='./git/%s'%(source_url[2]))

    return json.dumps({'status':200,'message':'成功'},ensure_ascii=False)

    # for i in results:
    #     source_url = i[4]
    #     repo_path1 = os.path.join('./gitBinary', i[2])
    #     sqliteTools.mkdir(repo_path1)
    #     repo_path = os.path.join('./git', i[2])
    #     # result = os.path.exists(repo_path)
    #     if os.path.exists(repo_path) == False:
    #        new_repo = git.Repo.clone_from(source_url, repo_path)
    #     print('======0000')   
        
    #     # copy file
    #     result = baseTools.list_file_name(repo_path) 
    #     for item in result:
    #         if item.startswith('.git'):
    #          continue
    #         filePath = './git/' + i[2] + '/' + item
    #         newPath = './gitBinary/' + i[2] + '/' 
    #         newPathFile = './gitBinary/' + i[2] + '/'  + item
    #         baseTools.copyAllFiletoPath(filePath,newPath,newPathFile)
        
    #     # os.makedirs("./git/%s"%(i[2]))
    #     # new_repo = git.Repo.clone_from(url=source_url, to_path='./git/%s'%(source_url[2]))

    # return json.dumps({'status':200,'message':'成功'},ensure_ascii=False)
   
# 查询接口
@app.route('/query/pods',methods=['post'])
def query_lists():  
    values = sqliteTools.queryKeyvalues(database='poddata.db',table='pod_trace_log')
    if values is None :
        return json.dumps({'status':400,'message':'查询出错'},ensure_ascii=False)
    arr=[]
    for i in values:
     print(i)
     arr.append({'id':i[0],'podName':i[2],'podSource':i[3],'auth':i[5],'podEmail':i[6]})
    # return json.dumps(arr, ensure_ascii=False)
    return json.dumps({'status':200,'data':arr}, ensure_ascii=False)

# 插入接口
@app.route('/insert/pods',methods=['put'])
def insert_data():  
    # podName = isNullString(default=request.form.get('podName'),value="0.1.0")
    # podSource  = isNullString(request.form.get('podSource'),"guohq")
    podName = isNullString(value=request.form.get('podName'),default="")
    repoName = isNullString(value=request.form.get('repoName'),default="")
    podspecName = isNullString(value=request.form.get('podspecName'),default="")
    podSource = isNullString(value=request.form.get('podSource'),default="")
    libURL = isNullString(value=request.form.get('libURL'),default="")
    # print(podName)
    # print(podName.isalnum())
    if re.match(r'^https?:/{2}\w.+$', podSource):
        print('合发')
    else:
        print('不合发')
    # print('git@' in podSource)

    if podName.isalnum() is False:
          return json.dumps({'status':400,'message':'podName 不合法'},ensure_ascii=False)
    if repoName.isalnum() is False:
          return json.dumps({'status':400,'message':'repoName 不合法'},ensure_ascii=False)
    if 'git@' in podSource:  
        print()
    else:        
     if regex.match(podSource) is None:
            return json.dumps({'status':400,'message':'podName 网址链接不合发'},ensure_ascii=False)
    if 'git@' in libURL:  
        print()
    else:        
     if regex.match(libURL) is  None:
            return json.dumps({'status':400,'message':'libURL 网址链接不合发'},ensure_ascii=False)

    # podspecName = isNullString(request.form.get('podSource'),podName)
    database_connect, database_cur = sqliteTools.connectDB(database='poddata.db')
    inserValues=[podName,repoName,podSource,libURL,'guo','820003039@qq.com',podspecName]   
    print(podName)  
    if podName is None:
        return json.dumps({'status':400,'message':'podName 为空'},ensure_ascii=False)
    elif podSource is None:
        return json.dumps({'status':400,'message':'podSource 为空'},ensure_ascii=False)
    else:
        sqliteTools.insert_database_table(database_cur=database_cur,database_connect=database_connect,table_name='pod_trace_log',values=inserValues)
        return json.dumps({'status':200,'message':'成功'},ensure_ascii=False)

@app.route('/login',methods=['get'])
def login_fun():
        return json.dumps({'status':200,'message':'成功'},ensure_ascii=False)

if __name__== '__main__':
    app.run(debug=True)